<template>
	<a-modal
		:visible="visible"
		width="90vw"
		wrap-class-name="a-modal-tab-dialog"
		centered
		destroyOnClose
		@cancel="cancel"
		:footer="null"
		:maskClosable="false">
		<template #title>
			<div class="a-modal-tab-title" style="height: 56px">
				<a-card
					v-if="detailInfo"
					class="dialog-card-container"
					:tab-list="detailTabs.map((item:any) => ({key: item, tab: item}))"
					:active-tab-key="activeKey"
					@tabChange="(key:any) => (activeKey = key)" />
			</div>
		</template>
		<div class="flex-container-nomal" style="height: 85vh">
			<template v-if="detailInfo">
				<div class="flex1 auto-y">
					<a-row style="min-height: 100%">
						<a-col :span="isApproval && ['退租信息', '合约信息', '业主信息', '账单信息','分阶信息'].includes(activeKey) ? 17 : 24" :class="{'contract-information-left': isApproval}">
							<lease-cancellation-information :data-source="detailInfo" v-if="activeKey == '退租信息'" />

							<contract-particulars
								:data-source="detailInfo"
								v-if="activeKey == '合约信息'"
								@success="getDetail"
								:approvalStatus="approvalStatus" />

							<occupant-information
								:approvalStatus="approvalStatus"
								v-if="activeKey == '业主信息'"
								:data-source="detailInfo.renterInfo || {}"
								:contract-type="contractType"
								:enter-renter-info="detailInfo.enterRenterInfo || {}"
								:detail-info="detailInfo || {}"
								:contract-id="contractId"
								@success="getDetail(false)" />

							<bill-tabs
								:approvalStatus="approvalStatus"
								:type="detailInfo.type"
								:query="{bizId: contractId, houseId: detailInfo.houseId, order: 'asc'}"
								:isValid="null"
								v-if="activeKey == '账单信息'"
								:contractType="3" />

							<delivery-note-information
								:is-enter-prise-contract="Boolean(detailInfo.enterPriseContractId)"
								:contract-id="contractId"
								:sign-type="detailInfo.signType"
								:house-id="detailInfo.houseId"
								v-if="activeKey == '物业交割单'" />

							<out-delivery-note-information v-if="activeKey == '退房交割单'" :contract-id="contractId" />

							<graded-info v-if="activeKey == '分阶信息'" :detail-info="detailInfo || {}" :contract-id="contractId" />
						</a-col>
						<a-col
							v-if="isApproval && ['退租信息', '合约信息', '业主信息', '账单信息','分阶信息'].includes(activeKey)"
							:span="7"
							class="approval-process-list-right">
							<div class="d-module-title">
								<b>审批信息</b>
							</div>

							<a-timeline style="margin-top: 25px">
								<a-timeline-item v-for="(progressItem, progressIndex) in approvalSpeedProgress" :key="progressItem.id">
									<template v-if="progressItem.type == '0'">
										<a-tag color="processing" style="border-radius: 12px; margin-bottom: 10px">发起申请</a-tag>
										<a-descriptions layout="vertical" bordered size="small">
											<a-descriptions-item>
												<template #label>
													<div class="flex-space-between">
														<span>发起人：{{ progressItem.initiatorName }}</span>
														<span>{{ progressItem.operationDate }}</span>
													</div>
												</template>
												<a-row style="line-height: 30px">
													<a-col :span="24">
														<a-space :size="10">
															<span class="default-color">
																抄送人(已抄送{{ progressItem.sendPersonList.length }}人)
															</span>
															<span
																v-if="progressItem.sendPersonList.length - progressItem.readCount > 0"
																class="warning-color">
																{{ progressItem.sendPersonList.length - progressItem.readCount }}人未读
															</span>
														</a-space>
													</a-col>
													<a-col :span="24">
														<a-tag
															v-for="(item, index) in progressItem.sendPersonList"
															color="#EFF1F4"
															style="color: #4e5969"
															:key="item.name">
															<svg-icon
																:icon-class="`icon-contract-approval${item.readStatus ? '1' : '0'}`" />
															{{ item.name }}
														</a-tag>
													</a-col>
												</a-row>
											</a-descriptions-item>
										</a-descriptions>
									</template>
									<template v-else>
										<template v-if="progressItem.nodeStatus != 4">
											<template v-for="(item, index) in progressItem.approvalPersonList" :key="item.name">
												<a-tag
													:color="approvalStatusList[item.approvalStatus].color"
													style="border-radius: 12px; margin-bottom: 10px">
													{{ approvalStatusList[item.approvalStatus].name }}
												</a-tag>
												<a-descriptions layout="vertical" bordered size="small" style="margin-bottom: 10px">
													<a-descriptions-item>
														<template #label>
															<div class="flex-space-between">
																<span>审批人：{{ item.name }}</span>
																<span>{{ item.approvalTime }}</span>
															</div>
														</template>
														<a-row style="line-height: 30px">
															<a-col :span="24">
																<a-space :size="10">
																	<span class="default-color">审批类型：</span>
																	<span>{{ progressItem.approvalType == 1 ? '或签' : '会签' }}</span>
																</a-space>
															</a-col>
															<a-col :span="24" v-if="[2, 3].includes(item.approvalStatus)">
																<a-space :size="10">
																	<span class="default-color">备注：{{ item.approvalComment }}</span>
																</a-space>
															</a-col>
														</a-row>
													</a-descriptions-item>
												</a-descriptions>
											</template>
											<a-descriptions layout="vertical" bordered size="small" style="margin-bottom: 10px">
												<a-descriptions-item>
													<template #label>
														<div class="flex-space-between">
															<span>抄送人</span>
														</div>
													</template>
													<a-row style="line-height: 30px">
														<a-col :span="24">
															<a-space :size="10">
																<span class="default-color">
																	抄送人(已抄送{{ progressItem.sendPersonList.length }}人)
																</span>
																<span
																	v-if="progressItem.sendPersonList.length - progressItem.readCount > 0"
																	class="warning-color">
																	{{ progressItem.sendPersonList.length - progressItem.readCount }}人未读
																</span>
															</a-space>
														</a-col>
														<a-col :span="24">
															<a-tag
																v-for="(item, index) in progressItem.sendPersonList"
																color="#EFF1F4"
																style="color: #4e5969"
																:key="item.name">
																<svg-icon
																	:icon-class="`icon-contract-approval${item.readStatus ? '1' : '0'}`" />
																{{ item.name }}
															</a-tag>
														</a-col>
													</a-row>
												</a-descriptions-item>
											</a-descriptions>
										</template>
										<template v-else>
											<a-tag color="default" style="border-radius: 12px; margin-bottom: 10px">已撤销</a-tag>
										</template>
									</template>
								</a-timeline-item>
							</a-timeline>
						</a-col>
					</a-row>
				</div>
				<!-- 审批页面调详情 -->
				<template v-if="isApproval">
					<template v-if="approvalType === 'todo'">
						<!-- 非前合同 -->
						<div
							class="a-modal-dialog-footer"
							v-if="
								!isPriorContract &&
								![5, 9].includes(detailInfo.contractStatus) &&
								[2].includes(detailInfo.signType) &&
								activeKey == '合约信息'
							">
							<a-button type="primary" :loading="loading" :disabled="loading" @click="getDetail(false, !isPriorContract)">
								续租前合同
							</a-button>
						</div>
						<!-- 前合同 -->
						<div class="a-modal-dialog-footer" v-else-if="isPriorContract && activeKey == '合约信息'">
							<a-button type="primary" :loading="loading" :disabled="loading" @click="getDetail(false, !isPriorContract)">
								查看合同
							</a-button>
						</div>
					</template>
				</template>
				<template v-else>
					<template v-if="
							[2, 4].includes(detailInfo.approvalStatus) &&
							![6].includes(detailInfo.contractStatus) &&
							store.hasPermissions(['mk_contract_owner_yzqy','mk_contract_owner_yzzf'])
						">
						<div class="a-modal-dialog-footer" v-if="operationVisible && activeKey == '合约信息'">
							<a-space :size="12">
								<a-button danger v-if="store.hasPermissions(['mk_contract_owner_yzzf'])" @click="handler('showToVoid')">
									作废
								</a-button>
								<!-- 补签审批撤销子合同详情不予许重新提交 additional===2 -->
								<a-button
									type="primary"
									v-if="store.hasPermissions(['mk_contract_owner_yzqy'])"
									@click="handler('resubmit')">
									重新提交
								</a-button>
							</a-space>
						</div>
					</template>

					<template v-else-if="[-1, 0, 3].includes(detailInfo.approvalStatus)">
						<div
							class="a-modal-dialog-footer"
							v-if="
								ownerStatus[detailInfo.contractStatus].operation.length &&
								activeKey == '合约信息' &&
								morePermissions(operationList)
							">
							<a-space :size="12">
								<template v-for="(operationItem, operationIndex) in operationList" :key="operationIndex">
									<template v-if="store.hasPermissions(operationItem.action)">
										<a-button danger v-if="operationItem.type == 'danger'" @click="handler(operationItem.field)">
											{{ operationItem.name }}
										</a-button>
										<a-button v-else :type="operationItem.type" @click="handler(operationItem.field)">
											{{ operationItem.name }}
										</a-button>
									</template>
								</template>
							</a-space>
						</div>
					</template>
				</template>
				<!-- 非审批页面调详情 -->
			</template>
		</div>
		<!-- 弹窗 -->
		<template v-if="visible && detailInfo">
			<!-- 续租 -->
			<owner-sign
				v-model:visible="operationField.showSignContract"
				:contract-id="contractId"
				:reset="reset"
				:contract="modalConfirmData.seveDate"
				@close="getDetail(false)"
				@success="getDetail" />
			<!-- 作废,重置 -->
			<operate-model v-model:visible="operationField.showToVoid" :data="modalConfirmData" @success="operateSuccess" />
			<!-- 重置 -->
			<!-- <reset-dialog v-model:visible="operationField.showReset" @success="operationField.showSignContract = true" /> -->
			<!-- 退租 -->
			<owner-retreat-rent v-model:visible="operationField.showRetreatRent" :contract-id="contractId" @success="getDetail" />
		</template>
	</a-modal>
</template>
<script setup lang="ts">
	import {ownerStatus} from '@/utils/tenant-status'
	import {getFollowList, getOwnerContractDetail, ownerContractResetValid, ownerContractObsolete} from '@/api/contract'
	import {reactive, ref, watch,onMounted} from 'vue'
	import LeaseCancellationInformation from '@/components/contract/contract-detail-dialog/lease-cancellation-information.vue'
	import ContractParticulars from '@/components/contract/owner-modal/detail/contract-particulars.vue'
	import OccupantInformation from '@/components/contract/owner-modal/detail/occupant-information.vue'
	import DeliveryNoteInformation from '@/components/contract/owner-modal/detail/delivery-note-information.vue'
	import OutDeliveryNoteInformation from '@/components/contract/contract-detail-dialog/out-delivery-note-information.vue'
	import OperateModel from '@/components/contract/owner-modal/operate/index.vue'
	import OwnerSign from '@/components/contract/signing/owner-sign.vue'
	import OwnerRetreatRent from '@/components/contract/owner-modal/owner-retreat-rent/index.vue'
	import GradedInfo from '@/components/contract/owner-modal/detail/graded-info.vue'
	import dayjs from 'dayjs'
	import {useStore} from '@/store/index'
	import {RenterContract} from '@/interface/contract'
	import BillTabs from '@/components/finance/bill-tabs.vue'
	import {microApps} from '@/micros/apps'
	import {Modal, message} from 'ant-design-vue'

	const store = useStore()

	const props = withDefaults(
		defineProps<{
			visible: boolean
			contractId: string
			// 是否显示按钮
			operationVisible?: boolean
			data?: any
			// 判断是否来源于主应用
			source?: string
			// 判断是否是审批
			isApproval?: boolean
			// 审批模块类型
			approvalType?: string|number
			// 审批模块
			processInstanceId?: string
		}>(),
		{
			visible: false,
			contractId: '',
			data: {},
			source:''
		}
	)
	//是否重新提交
	const isResubmit = ref(false)
	const reset = ref(false)
	const contractType = ref(null)

	const invitationSignature = reactive<any>({
		name: '',
		phone: '',
		contractId: ''
	})
	const emit = defineEmits(['update:visible', 'close'])
	const cancel = () => {
		emit('update:visible', false)
		emit('close')
		detailInfo.value = null
		microApps.removeApp('device')
	}
	const approvalStatus = ref('-1')

	const activeKey = ref('合约信息')
	const detailInfo = ref<any>(null)
	const detailTabs = ref<any>([])
	const contractMedium = ref<any>(null)
	// const approvalData = reactive({
	// 	title: 0,
	// 	taskId: detailInfo.value.taskId
	// })
	//操作相关参数
	const modalConfirmData = reactive<any>({
		title: null,
		content: null,
		requestMethodFun: null,
		seveDate: null
	})
	const morePermissions = (permissions: any) => {
		let permissionsList: any = []
		permissions.forEach((item: any) => {
			if (item.action[0]) {
				permissionsList.push(item.action[0])
			}
		})
		return store.hasPermissions(permissionsList)
	}

	const operationList = ref<any>([])
	const renterInfo = ref<any>({})
	const isPriorContract = ref(false)
	const loading = ref(false)
	const getDetail = async (flag = true, before = false) => {
		loading.value = true
		let res: any = await getOwnerContractDetail(before ? detailInfo.value.contractPid : props.contractId)
		if (res) {
			isPriorContract.value = before
			loading.value = false
			if (res.code == 200) {
				console.log(res, '0099')

				contractType.value = res.data.contractType
				approvalStatus.value = res.data.approvalStatus
				let statusInfo = {
					name: ownerStatus[res.data.contractStatus].name,
					color: ownerStatus[res.data.contractStatus].color
				}

				if (res.data.rentFreeDay > 0) {
					res.data.rentFreeEndTime = dayjs(res.data.rentFreeBeginTime)
						.add(res.data.rentFreeDay, 'day')
						.subtract(1, 'day')
						.format('YYYY-MM-DD')
				}
				detailInfo.value = {...res.data, statusInfo}
				if (props.isApproval) {
					detailTabs.value = ownerStatus[detailInfo.value.contractStatus].detailTab.filter((item: any) => {
						return !['退房交割单'].includes(item)
					})
					if (props.approvalType === 'todo' && !isPriorContract.value && [5,9].includes(detailInfo.value.contractStatus)) {
						detailTabs.value = [ '退租信息',...detailTabs.value, '退房交割单']
					}
				} else {
					detailTabs.value = ownerStatus[detailInfo.value.contractStatus].detailTab
				}
				if (flag) {
					activeKey.value = detailTabs.value[0]
				}

				invitationSignature.name = res.data.renterInfo.name
				invitationSignature.phone = res.data.renterInfo.phone
				invitationSignature.contractId = res.data.renterInfo.contractId
				// 操作
				operationList.value = [...ownerStatus[res.data.contractStatus].operation].sort((a: any, b: any) => a.sort - b.sort)
				console.log(operationList.value, '999')

				// 作废和提醒付款数据
				renterInfo.value = {
					name: res.data.renterInfo.name,
					phone: res.data.renterInfo.phone,
					contractPid: res.data.contractPid,
					contractId: props.contractId,
					houseId: res.data.houseId
				}
			}
		}
	}

	const approvalStatusList: any = {
		0: {
			name: '待审批',
			color: 'default'
		},
		1: {
			name: '审批中',
			color: 'processing'
		},
		2: {
			name: '已驳回',
			color: 'error'
		},
		3: {
			name: '已通过',
			color: 'success'
		},
		4: {
			name: '已撤销',
			color: 'default'
		}
	}

	const approvalSpeedProgress = ref<any>({})
	// 获取审批进度信息列表
	const getApprovalDetail = () => {
		getFollowList({
			processInstanceId: props.processInstanceId
		}).then((res: any) => {
			approvalSpeedProgress.value = res.data
			console.log(res, '审批进度')
		})
	}

	type statementField = {
		[key: string]: boolean
	}
	// const contractType = ref(3)
	// 操作按钮
	const operationField = reactive<statementField>({
		//签约业主合同
		showSignContract: false,
		// 查看详情
		detailVisible: false,
		// 拒绝
		showRefuse: false,
		// 提醒付款
		showRemindPay: false,
		// 作废
		showToVoid: false,
		// 重置
		showReset: false,
		// 退租
		showRetreatRent: false
	})
	const operateSuccess = () => {
		getDetail()
	}
	// 合同签约信息
	const signContract = ref<RenterContract>({})
	const handler = (field: string) => {
		// signContract.value = XEUtils.clone(detailInfo.value, true)
		// signContract.value.reset = false
		// signContract.value.resubmit = false
		if (field == 'showToVoid') {
			modalConfirmData.title = '作废'
			modalConfirmData.content = `作废会删除该合同收支，确定要作废[${detailInfo.value.renterInfo.name}/${detailInfo.value.renterInfo.phone}]的合同吗?`
			modalConfirmData.requestMethodFun = ownerContractObsolete
			modalConfirmData.seveDate = {contractId: detailInfo.value.id, houseId: detailInfo.value.houseId}
			operationField.showToVoid = true
		} else if (field == 'showSignContract') {
			//续租
			modalConfirmData.seveDate = detailInfo.value
			modalConfirmData.seveDate.signType = 2
			operationField.showSignContract = true
		} else if (field == 'showReset') {
			//重置
			modalConfirmData.seveDate = {contractId: detailInfo.value.id, houseId: detailInfo.value.houseId}
			modalConfirmData.seveDate.signType = 1
			reset.value = true
			// contractId.value = detailInfo.contractId
			getOwnerContractResetValid()
		} else if (field == 'resubmit') {
			//
			isResubmit.value = true
			if (detailInfo.value.contractStatus === 9 || detailInfo.value.label === 5) {
				//重新提交退租
				isResubmit.value = true
				operationField.showRetreatRent = true
				return
			}

			signContract.value.resubmit = true
			operationField['showSignContract'] = true
		} else if (field === 'printReport') {
			// downloadReport(detailInfo.value)
		} else {
			operationField[field] = true
		}
	}
	const getOwnerContractResetValid = () => {
		ownerContractResetValid(detailInfo.value.id).then(({data}) => {
			if (data) {
				isResubmit.value = true
				operationField.showSignContract = true
			} else {
				message.error('已产生收支无法重置')
			}
		})
	}

	watch([() => props.visible], (newVal, oldVal) => {
		if (newVal[0]) {
			console.log(props)
			getDetail()
		}
	})

	onMounted(() => {
		if (props.source === 'dialog') {
			getDetail()

			if (props.isApproval && props.processInstanceId) {
				console.log(props.processInstanceId)
				getApprovalDetail()
			}
		}
	})

	const showBtn = () => {
		let temp = true
		if (detailInfo.value.enterPriseContractId && detailInfo.value.signType === 2) {
			temp = false
		}
		return temp
	}
</script>
<style lang="less">
	.contract-information-left {
		min-height: 100%;
		padding-right: 15px;
		border-right: 1px solid @border-color-light;
	}

	.approval-process-list-right {
		min-height: 100%;
		padding-left: 15px;
	}
</style>
